import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wangxin
 * Date: 2024-11-24
 * Time: 20:54
 */
public class test1 {
    //解法一
    public boolean isValid (String s) {
        // write code here
        if(s.length() == 0){
            return true;
        }
        Stack<Character> stack = new Stack<>();
        for(int i = 0;i < s.length();i++){
            if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{'){
                stack.push(s.charAt(i));
            }else{
                if(stack.size() == 0){
                    return false;
                }
                if((s.charAt(i)==')'&&stack.peek()=='(')||(s.charAt(i)=='}'
                        &&stack.peek()=='{')||(s.charAt(i)==']'&&stack.peek()=='[')){
                    stack.pop();
                }else{
                    return false;
                }
            }
        }
        if(stack.size() == 0){
            return true;
        }
        return false;
    }

    //解法二
    public boolean isValid2 (String s) {
        // write code here
        if(s.length() == 0){
            return true;
        }
        Stack<Character> stack = new Stack<>();
        for(int i = 0;i < s.length();i++){
            if(s.charAt(i) == '('){
                stack.push(')');
            }else if(s.charAt(i) == '['){
                stack.push(']');
            }else if(s.charAt(i) == '{'){
                stack.push('}');
            }else if(stack.isEmpty() || stack.pop()!= s.charAt(i)){
                return false;
            }
        }

        return stack.isEmpty();
    }
}
